/**
 * 通用按钮基类，皮肤界面一律使用BaseButton，禁止使用eui.Button
 * @author wyd
 */
class BaseButton extends eui.Button {

	public isClickAnim:boolean = true;

	private _tapFunction:Function;
	private _scope:any;
	private _redPoint:eui.Image;

	/**
	 * 设置红点状态
	 */
	public set redPoint(state:boolean){
		if(state){
			this.showRedPoint();
		}else{
			this.hideRedPoint();
		}
	}

	public constructor() {
		super();
	}

	protected childrenCreated(){
		super.childrenCreated();
		this.init();
	}

	private init(){
		this.addEventListener(egret.Event.REMOVED_FROM_STAGE, this.onRemoveToStageHandler, this);
	}

	private onRemoveToStageHandler(e:egret.Event){
		this.clear();
	}

	/**
	 * 按钮点击动画
	 */
	private playClickAnim(){
		if(this.isClickAnim){
			EffectUtil.instance().playBtnEffect(this);
		}
		SoundManager.instance().playSound('button_mp3');
	}

	/**
	 * 添加点击回调
	 * @param call 回调
	 * @param scope 作用域
	 */
	public addTapHandler(call:Function, scope:any){
		this._tapFunction = call;
		this._scope = scope;
		if(!this.hasEventListener(egret.TouchEvent.TOUCH_TAP)){
			this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTapHandler, this);
		}
	}

	/**
	 * 移除点击监听
	 */
	public removeTapHandler(){
		if(this.hasEventListener(egret.TouchEvent.TOUCH_TAP)){
			this.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTapHandler, this);
		}
		this._tapFunction = null;
		this._scope = null;
	}

	private onTapHandler(e:egret.TouchEvent){
		this.playClickAnim();
		egret.Tween.get(this).wait(200).call(()=>{
			if(this._tapFunction && this._scope){
				this._tapFunction.call(this._scope);
			}
		});
	}

	/**
	 * 显示红点
	 */
	private showRedPoint(){
		if(!this._redPoint){
			this._redPoint = new eui.Image();
			this._redPoint.source = RES.getRes('red_point_png');
			this._redPoint.top = 0;
			this._redPoint.right = 0;
		}
		if(!this._redPoint.parent){
			this.addChild(this._redPoint);
		}
	}

	/**
	 * 隐藏红点
	 */
	public hideRedPoint(){
		if(this._redPoint && this._redPoint.parent){
			this._redPoint.parent.removeChild(this._redPoint);
		}
	}

	public clear(){
		this.removeEventListener(egret.Event.REMOVED_FROM_STAGE, this.onRemoveToStageHandler, this);
		this.removeTapHandler();
		this.hideRedPoint();
		this.isClickAnim = null;
		this._redPoint = null;
		egret.Tween.removeTweens(this);
	}
}

window['BaseButton'] = BaseButton;